/**
 * @Author:Geln Yang
 * @Created:2008-7-29
 * $ Revision: 1.0 $
 * $ Author: Geln Yang $
 * $ Date: 2008-7-29 $
 */
package org.geln.file;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @Author:Geln Yang
 * @Created:2008-7-29
 */
public class FileUtil {

	public static String SYSTEM_ENCODING = System.getProperty("file.encoding");

	public static String getFileFullName(String file) {
		return file;
	}

	public static String getFileType(String file) {
		if (file != null) {
			int start = file.lastIndexOf(".");
			if (start > 0) {
				return file.substring(start + 1);
			}
		}
		return null;

	}

	public static File getDirectory(String dir) {
		if (dir != null) {
			File directory = new File(dir);
			if (!directory.exists()) {
				directory.mkdir();
			}
			return directory;
		}
		return null;
	}

	public static File getFile(String f) {
		if (f != null) {
			File file = new File(f);
			if (!file.exists()) {
				try {
					file.createNewFile();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return file;
		}
		return null;
	}

	public static StringBuffer getStringBuffer(File f, String charset) {
		try {
			FileInputStream fs = new FileInputStream(f);
			InputStreamReader s = new InputStreamReader(fs, charset);
			StringBuffer sb = new StringBuffer();
			int c;
			while ((c = s.read()) != -1) {
				sb.append((char) c);
			}
			return sb;
		} catch (FileNotFoundException e) {
			return null;
		} catch (IOException e) {
			return null;
		}
	}

	public static StringBuffer getStringBuffer(String f, String charset) {
		if (f != null) {
			File file = new File(f);
			if (file.exists()) {
				return getStringBuffer(file, charset);
			}
		}
		return null;
	}

	public static StringBuffer getStringBuffer(File f) {
		return getStringBuffer(f, SYSTEM_ENCODING);
	}

	public static StringBuffer getStringBuffer(String f) {
		return getStringBuffer(f, SYSTEM_ENCODING);
	}
}
